﻿using System.ComponentModel;
using System.Collections.Generic;
namespace ShpMerger
{
    public class ShapeFileMerger
    {
        public ShapeFileMerger()
        { }

        /// <summary>
        ///Merge all files to outfile. 
        /// </summary>
        /// <param name="SourceFiles">IEnumerable of source files</param>
        /// <param name="targetFile">the target file</param>
        public bool Merge(IEnumerable<string> SourceFiles, string targetFile)
        {
            if (SourceFiles == null || targetFile == null)
            {
                return false;
            }
            ShpFile outFile = new ShpFile(targetFile, ShapeFileOpenMode.FileCreate);
            foreach (string file in SourceFiles)
            {
                ShpFile mergeFile = new ShpFile(file, ShapeFileOpenMode.FileRead);
                outFile.Merge(mergeFile);
                mergeFile.Close();
            }
            outFile.Close();
            return true;
        }

        /// <summary>
        ///Merge all files to outfile with the progress.
        /// </summary>
        /// <param name="SourceFiles">the source files</param>
        /// <param name="outFile">the target file</param>
        /// <param name="worker">BackgroundWorker param</param>
        /// <param name="e"> DoWorkEventArgs param</param>
        public bool Merge(string[] SourceFiles, string targetFile, BackgroundWorker worker, DoWorkEventArgs e)
        {
            if (SourceFiles == null || targetFile == null )
            {
                return false;
            }
            ShpFile outFile = new ShpFile(targetFile, ShapeFileOpenMode.FileCreate);
            for (int i = 0; i < SourceFiles.Length; i++)
            {
                ShpFile mergeFile = new ShpFile(SourceFiles[i], ShapeFileOpenMode.FileRead);
                outFile.Merge(mergeFile);
                mergeFile.Close();
                int percentComplete = (int)((float)(i + 1) / (float)SourceFiles.Length * 100);
                worker.ReportProgress(percentComplete);
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    outFile.Close();
                    return true;
                }
                // If look the progress effect, add the delay.
                // Thread.Sleep(500);
            }
            outFile.Close();
            return true;
        }
    }
}
